package com.example.carrierapp.util;

import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Administrator on 2016/12/7.
 */
public class GetLatAndLngByBaidu {
    static double DEF_PI = 3.14159265359; // PI
    static double DEF_2PI = 6.28318530712; // 2*PI
    static double DEF_PI180 = 0.01745329252; // PI/180.0
    static double DEF_R = 6370693.5; // radius of earth

    //    String key = "5mrOB8ASOkKRMlcDuIWgLqTq2zRCuFpp";
    String key = "5mrOB8ASOkKRMlcDuIWgLqTq2zRCuFpp";
//    String key = "f247cdb592eb43ebac6ccd27f796e2d2";

    /**
     * @param addr 查询的地址
     * @return
     * @throws IOException
     */
    public Object[] getCoordinate(String addr) {
        Double lng = null;//经度
        Double lat = null;//纬度
        if (addr == null) {
            return null;
        }
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", addr, key);
        String json = loadJSON(url);
        Log.i("TAG", "addr" + addr);
        Log.i("TAG", "json" + json);
        if (json == null) {
            return null;
        }
        try {
            JSONObject obj = new JSONObject(json);
            if (obj.get("status").toString().equals("OK")) {
                lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
                lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
                System.out.println("经度："+lng+"---纬度："+lat);
            } else {
                System.out.println("未找到相匹配的经纬度！");
                return null;
            }

        } catch (Exception e) {

        }
        return new Object[]{lng, lat};
    }

    private String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream()));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
        }
        return json.toString();
    }

    //适用于远距离
    public static double GetLongDistance(double lon1, double lat1, double lon2, double lat2) {
        double ew1, ns1, ew2, ns2;
        double distance;
        // 角度转换为弧度
        ew1 = lon1 * DEF_PI180;
        ns1 = lat1 * DEF_PI180;
        ew2 = lon2 * DEF_PI180;
        ns2 = lat2 * DEF_PI180;
        // 求大圆劣弧与球心所夹的角(弧度)
        distance = Math.sin(ns1) * Math.sin(ns2) + Math.cos(ns1) * Math.cos(ns2) * Math.cos(ew1 - ew2);
        // 调整到[-1..1]范围内，避免溢出
        if (distance > 1.0)
            distance = 1.0;
        else if (distance < -1.0)
            distance = -1.0;
        // 求大圆劣弧长度
        distance = DEF_R * Math.acos(distance);
        return distance;
    }
}
//
//    public Object[] getCoordinate(String addr) throws Exception {
//
//        String lng = null;//经度
//        String lat = null;//纬度
//        String address = null;
//        try {
//            address = java.net.URLEncoder.encode(addr, "UTF-8");
//        } catch (Exception e1) {
//            e1.printStackTrace();
//        }
//        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
//        URL myURL = null;
//        URLConnection httpsConn = null;
//        try {
//            myURL = new URL(url);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }
//        InputStreamReader insr = null;
//        BufferedReader br = null;
//        try {
//            httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
//            if (httpsConn != null) {
//                insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
//                br = new BufferedReader(insr);
//                String data = null;
//                int count = 1;
//                while ((data = br.readLine()) != null) {
//                    if (count == 5) {
//                        lng = (String) data.subSequence(data.indexOf(":") + 1, data.indexOf(","));//经度
//                        count++;
//                    } else if (count == 6) {
//                        lat = data.substring(data.indexOf(":") + 1);//纬度
//                        count++;
//                    } else {
//                        count++;
//                    }
//                }
//            }
//        } catch (Exception e) {
//
//        } finally {
//            if (insr != null) {
//                insr.close();
//            }
//            if (br != null) {
//                br.close();
//            }
//        }
//        return new Object[]{lng, lat};
//    }
//}
//    public Object[] getAdress(String ln, String la) {
//        String location = ln + "," + la;
//        String location1 = null;
//        try {
//            location1 = java.net.URLEncoder.encode(location, "UTF-8");
//        } catch (UnsupportedEncodingException e1) {
//            e1.printStackTrace();
//        }
//        String url = String.format("http://api.map.baidu.com/geocoder?location=%s&output=json&key=%s", location1, key);
//        URL myurl = null;
//        URLConnection httpsConn = null;
//        try {
//            myurl = new URL(url);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }
//        InputStreamReader insr = null;
//        BufferedReader br = null;
//        String s1 = null;
//        try {
//            httpsConn = (URLConnection) myurl.openConnection();
//            if (httpsConn != null) {
//                insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
//                br = new BufferedReader(insr);
//                String data = null;
//                int count = 1;
//                while ((data = br.readLine()) != null) {
//                    if (count == 7) {
//                        String adrsss = (String) data.subSequence(data.indexOf(":") + 1, data.indexOf(","));//经度
//                        Log.i("TAG", "adrsss" + adrsss);
//                        count++;
//                    } else {
//                        count++;
//                    }
//                    Log.i("TAG", data);
//                }
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            s1 = "未知地点";
//        } finally {
//            s1 = "未知地点";
//        }
//        return new Object[]{s1};
//    }
//}